package admin

import (
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"gitee.com/jikey/elk-blog/setting"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"strconv"
)

type Link struct {
	Base
}

func (l *Link) Index(c *gin.Context) {
	data := make(map[string]interface{})
	response.HTML(c, "link/index", data)
}

// List 列表
func (l *Link) List(c *gin.Context) {
	data := make(map[string]interface{})

	pageNum, _ := strconv.Atoi(c.Query("page"))

	title := c.Query("title")
	maps := "title like '%" + title + "%'"

	data["rows"] = service.Link.List(pageNum, setting.PageSize, maps)
	data["total"] = service.Link.Total(maps)

	response.Success(c, data)
}

// Insert 新增保存
func (l *Link) Insert(c *gin.Context) {
	banner := &model.Link{}

	if err := c.ShouldBind(&banner); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	err := service.Link.Create(banner)

	if err != nil {
		logrus.Error("修改失败", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	response.Success(c, banner)
}

// Update 修改
func (l *Link) Update(c *gin.Context) {
	link := &model.Link{}

	if err := c.ShouldBind(&link); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	id := strconv.Itoa(link.Id)
	err := service.Link.Update(id, link)

	if err != nil {
		logrus.Error("修改失败： ", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	response.Success(c, link)
}

// Destory 删除
func (l *Link) Destory(c *gin.Context) {
	id := c.PostForm("id")
	service.Link.Delete(id)

	response.Success(c, id)
}
